package logic

import (
	"context"
	"encoding/json"
	"product/model/mysql"
	"product/model/redis"
	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserListLogic) UserList(in *productrpc.UserListRequest) (*productrpc.UserListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	size := in.Size
	if page <= 0 {
		page = 1
	}
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	offset := (page - 1) * size

	var product []mysql.Product

	itoa := strconv.Itoa(int(offset))

	get := redis.Client.Get("productList" + itoa)

	if get.Val() == "" {
		mysql.DB.Debug().Offset(int(offset)).Limit(int(size)).Order("price desc").Find(&product)

		marshal, _ := json.Marshal(&product)

		redis.Client.Set(get.Val(), marshal, time.Minute*5)
	} else {
		json.Unmarshal([]byte(get.Val()), &product)
	}

	var productList []*productrpc.UserList

	for _, m := range product {
		list := &productrpc.UserList{
			Img:   m.Img,
			Name:  m.Name,
			Price: float32(m.Price),
			Num:   int64(m.Num),
			Id:    int64(m.ID),
		}
		productList = append(productList, list)
	}

	return &productrpc.UserListResponse{List: productList}, nil
}
